package com.erpanderp.wam.cm.view;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.Serializable;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpSession;

import org.primefaces.model.UploadedFile;

import com.erpanderp.wam.cm.model.entity.EmpPersonalResume;
import com.erpanderp.wam.cm.model.service.UploadResumeDAO;
import com.erpanderp.wam.usm.model.entity.user.WAMUser;
import com.erpanderp.wam.util.CommonLookup;

@ManagedBean
@ViewScoped
public class UploadPersonalResumeBean implements Serializable{

	private static final long serialVersionUID = 1L;
	private HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(true);
	private WAMUser wamUser = (WAMUser) session.getAttribute(CommonLookup.SESSION_ATTRIBUTE_WAMUSER);
	
	//private UploadedFile file;
	private UploadedFile empResume;
	private String fileName;
	private File realPath;
	private boolean FORM_VALID;
	private String moduleName;
	private String name;
	
	private EmpPersonalResume empPersonalResume;
	
	private UploadResumeDAO uploadResumeDAO=new UploadResumeDAO();
	
	public UploadPersonalResumeBean() {		
		moduleName = wamUser.getEmployee().getModuleName();
	}

	
	
	public String uploadEmpPersonalResumeAction() {				
		
		validateForm();
		if (FORM_VALID) {
		
		
		try{
			empPersonalResume = null;	 
			empPersonalResume= uploadResumeDAO.getEmployeeResumeByEmployeeId(wamUser.getEmployee().getEmployeeId());	
			    
			if(empPersonalResume == null){
				empPersonalResume = new EmpPersonalResume();
				System.out.println("================INSIDE IF=================");
				//set properties
				ExternalContext extContext=FacesContext.getCurrentInstance().getExternalContext();
				 fileName = empResume.getFileName();
				 System.out.println("FILE NAME :::::::::::::::::::::"+fileName);
				
				 String s = fileName.substring(fileName.lastIndexOf("."));
				 System.out.println("s EXT NAME  NAM ::::::::::::"+s);
				 String newFileName = wamUser.getEmployee().getEmployeeCode()+s;
				 System.out.println("NEW FILE NAM ::::::::::::"+newFileName);
				 
				 Pattern pattern = Pattern.compile("[^a-zA-Z\\s]");
				 Matcher matcher = pattern.matcher(moduleName);
				 String module = matcher.replaceAll("");				 
				 
				 File sss= new File(extContext.getRealPath("//employeePersonalResumes//"+module+"//"));
				 boolean isDirectoryCreated = sss.mkdir();
				 //setRealPath(new File(sss+"//"+empResume.getFileName()));
				 setRealPath(new File(sss+"//"+newFileName));
				 Object fileSize = getEmpResume().getSize(); 
					
					empPersonalResume.setEmployee(wamUser.getEmployee());
					empPersonalResume.setModuleName(moduleName);
					//empPersonalResume.setFilename(fileName);
				   //empPersonalResume.setFilePath("\\"+module+"\\"+fileName);
					empPersonalResume.setFilename(newFileName);
					empPersonalResume.setFilePath("\\"+module+"\\"+newFileName);
					empPersonalResume.setFileSize(fileSize.toString());
					empPersonalResume.setUploadDate(new Date());
					empPersonalResume.setCreateDate(new Date());
					empPersonalResume.setCreatedBy(CommonLookup.CREATEDBY_DEVELOPER_TEXT);
					empPersonalResume.setStatus(CommonLookup.STATUS_ACTIVE);
					File rootPath= new File(extContext.getRealPath("//employeePersonalResumes//"));
					FileOutputStream fileOutputStream = new FileOutputStream(rootPath+empPersonalResume.getFilePath(),true);
					byte[] buffer = new byte[1024*1024*10];		//10MB
					int bulk;
				    InputStream inputStream = getEmpResume().getInputstream();
					while (true) {
						bulk = inputStream.read(buffer);
							if (bulk < 0) {
							 break;
							}
						fileOutputStream.write(buffer, 0, bulk);
						fileOutputStream.flush();
				   }
				 fileOutputStream.close();
				 inputStream.close();
				
				uploadResumeDAO.createEmployeePersonalResume(empPersonalResume);
			} else{
				System.out.println("================INSIDE ELSE=================");
				//set properties
				ExternalContext extContext=FacesContext.getCurrentInstance().getExternalContext();
				 fileName = empResume.getFileName();
				 System.out.println("FILE NAME :::::::::::::::::::::"+fileName);
				
				 String s = fileName.substring(fileName.lastIndexOf("."));
				 System.out.println("s EXT NAME  NAM ::::::::::::"+s);
				 String newFileName = wamUser.getEmployee().getEmployeeCode()+s;
				 System.out.println("NEW FILE NAM ::::::::::::"+newFileName);
				 
				 Pattern pattern = Pattern.compile("[^a-zA-Z\\s]");
				 Matcher matcher = pattern.matcher(moduleName);
				 String module = matcher.replaceAll("");				 
				 
				 File sss= new File(extContext.getRealPath("//employeePersonalResumes//"+module+"//"));
				 boolean isDirectoryCreated = sss.mkdir();
				 //setRealPath(new File(sss+"//"+empResume.getFileName()));
				 setRealPath(new File(sss+"//"+newFileName));
				 Object fileSize = getEmpResume().getSize(); 
					
					empPersonalResume.setEmployee(wamUser.getEmployee());
					empPersonalResume.setModuleName(moduleName);
					//empPersonalResume.setFilename(fileName);
				   //empPersonalResume.setFilePath("\\"+module+"\\"+fileName);
					empPersonalResume.setFilename(newFileName);
					empPersonalResume.setFilePath("\\"+module+"\\"+newFileName);
					empPersonalResume.setFileSize(fileSize.toString());
					empPersonalResume.setUploadDate(new Date());
					empPersonalResume.setCreateDate(new Date());
					empPersonalResume.setCreatedBy(CommonLookup.CREATEDBY_DEVELOPER_TEXT);
					empPersonalResume.setStatus(CommonLookup.STATUS_ACTIVE);
					File rootPath= new File(extContext.getRealPath("//employeePersonalResumes//"));
					FileOutputStream fileOutputStream = new FileOutputStream(rootPath+empPersonalResume.getFilePath(),true);
					byte[] buffer = new byte[1024*1024*10];		//10MB
					int bulk;
				    InputStream inputStream = getEmpResume().getInputstream();
					while (true) {
						bulk = inputStream.read(buffer);
							if (bulk < 0) {
							 break;
							}
						fileOutputStream.write(buffer, 0, bulk);
						fileOutputStream.flush();
				   }
				 fileOutputStream.close();
				 inputStream.close();
				
				uploadResumeDAO.createEmployeePersonalResume(empPersonalResume);
			} 
			     	
				 
				 //uploadResumeDAO.createEmployeePersonalResume(empPersonalResume);	
				 FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO,  " You have uploaded successfully.", ""));
				 empPersonalResume = new EmpPersonalResume();
			
			}catch (Exception e) {
				e.printStackTrace();
			}
		}
		
		return null;
	}
	
	// VALIDATIONS
		private void validateForm() {
			FORM_VALID = true;
		
			
			if(empResume.getFileName() == null || empResume.getFileName().equals("") ){
		    	FacesContext.getCurrentInstance().addMessage("", new FacesMessage(FacesMessage.SEVERITY_WARN, "Upload Resume cannot be empty", ""));
		    	FORM_VALID = false;
		    }else{
		    	String fileName =empResume.getFileName();
				 String fileExtention = fileName.substring(fileName.lastIndexOf(".")+1,fileName.length());
				 
				 if (fileExtention.equalsIgnoreCase("docx") || fileExtention.equalsIgnoreCase("doc") || fileExtention.equalsIgnoreCase("pdf") || fileExtention.equalsIgnoreCase("odt") )
		         {
					System.out.println("File should be any one of above specified format");

		         }else{
		        	 FORM_VALID = false;
					 FacesContext.getCurrentInstance().addMessage(null,new FacesMessage(FacesMessage.SEVERITY_WARN,"Invalid file type.File name should be in .docx,.doc,.pdf or .odt", ""));
		         }
			 
		    }
		}
	
	
	//GETTERS AND SETTERS
	
	public String getFileName() {
		return fileName;
	}


	public void setFileName(String fileName) {
		this.fileName = fileName;
	}


	public File getRealPath() {
		return realPath;
	}


	public void setRealPath(File realPath) {
		this.realPath = realPath;
	}


	public boolean isFORM_VALID() {
		return FORM_VALID;
	}


	public void setFORM_VALID(boolean fORM_VALID) {
		FORM_VALID = fORM_VALID;
	}

	public EmpPersonalResume getEmpPersonalResume() {
		return empPersonalResume;
	}

	public void setEmpPersonalResume(EmpPersonalResume empPersonalResume) {
		this.empPersonalResume = empPersonalResume;
	}

	public UploadResumeDAO getUploadResumeDAO() {
		return uploadResumeDAO;
	}

	public void setUploadResumeDAO(UploadResumeDAO uploadResumeDAO) {
		this.uploadResumeDAO = uploadResumeDAO;
	}

	public WAMUser getWamUser() {
		return wamUser;
	}

	public void setWamUser(WAMUser wamUser) {
		this.wamUser = wamUser;
	}

	public String getModuleName() {
		return moduleName;
	}

	public void setModuleName(String moduleName) {
		this.moduleName = moduleName;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public UploadedFile getEmpResume() {
		return empResume;
	}

	public void setEmpResume(UploadedFile empResume) {
		this.empResume = empResume;
	}

}
